//封装分类数据业务代码

import { getCategoryAPI } from "@/apis/category";
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";

import { onBeforeRouteUpdate } from "vue-router";

export function useCategory() {
    //获取数据
    const categoryData = ref({});
    const route = useRoute();
    const getCategory = async (id = route.params.id) => {
        const res = await getCategoryAPI(id);
        categoryData.value = res.result;
    };

    onMounted(() => {
        getCategory();
    });
    // watch(route, () => getCategory());
    //目标：路由参数变化时，可以将分类数据接口重新发送
    onBeforeRouteUpdate((to) => {
        //存在问题：使用最新的路与参数请求最新的分类数据
        // console.log("路由变化了");
        getCategory(to.params.id)
    })
    return {
        categoryData
    }

}